package com.huluobo.a2302mdmdemo.demo

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.view.animation.AccelerateInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout
import com.huluobo.a2302mdmdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.util.Random
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/8/6.
 */
class RedPackRainView(context: Context) : RelativeLayout(context) {
    //计时器,用于计算间隔多久生成一个红包
    private lateinit var timer: Timer

    fun start() {
        timer = Timer()
        timer.schedule(timerTask {
            CoroutineScope(Job()).launch(Dispatchers.Main) {
                val iv = ImageView(context)
                iv.setImageResource(R.drawable.like)
                val params = LayoutParams(100, 100)
                val left = Random().nextInt(980)
                params.topMargin = 0
                params.leftMargin = left
                iv.layoutParams = params

                val animator = ObjectAnimator.ofFloat(iv, "translationY", 0f, 1920f)
                animator.duration = 1000
                animator.interpolator = AccelerateInterpolator()
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        //当动画结束的时候移除掉iv
                        removeView(iv)
                    }
                })
                animator.start()
                addView(iv)
            }
        }, 0, 100)
    }
}